package org.yaac.shared.editor;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.yaac.shared.property.KeyInfo;

/**
 * the entity hierachy from root entity to the current entity
 * 
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
//TODO : implement ordering based on logics documented at http://code.google.com/appengine/docs/java/datastore/entities.html
public class EntityHierarchy implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * current entity key
	 */
	private KeyInfo key;
	
	/**
	 * entity keys info map
	 * 
	 * we don't use list becuase it is possible that entity info is null for some node
	 */
	private Map<KeyInfo, EntityInfo> infoMap;
	
	/**
	 * 
	 */
	@SuppressWarnings("unused")
	private EntityHierarchy(){}
	
	public EntityHierarchy(KeyInfo key, EntityInfo info){
		this.key = key;
		this.infoMap = new HashMap<KeyInfo, EntityInfo>();
		this.put(key, info);
	}
	
	public void put(KeyInfo key, EntityInfo info) {
		this.infoMap.put(key, info);
	}

	public KeyInfo getKey() {
		return key;
	}

	public EntityInfo lookupAncester(KeyInfo key) {
		return infoMap.get(key);
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((infoMap == null) ? 0 : infoMap.hashCode());
		result = prime * result + ((key == null) ? 0 : key.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		EntityHierarchy other = (EntityHierarchy) obj;
		if (infoMap == null) {
			if (other.infoMap != null)
				return false;
		} else if (!infoMap.equals(other.infoMap))
			return false;
		if (key == null) {
			if (other.key != null)
				return false;
		} else if (!key.equals(other.key))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "EntityHierarchy [key=" + key + ", infoMap=" + infoMap + "]";
	}
}
